#!/bin/bash
#


GREEN='\e[0;32m'
RED='\e[1;31m'
END='\e[0m'
RED()
{
	echo -e  "${RED}$1${END}"
}

GREEN()
{
	echo -e  "${GREEN}$1${END}"
}

USER_NAME=software
USER_PASSWORD=rocosw
RELEASE_HOST=192.168.122.220
RELEASE_BASE=/Release
RELEASE_TYPE=4G
RELEASE_PLATFORM=MT8735BD
ANDROID_VERSION=N0
ROCO_BOARD=LF705
RELEASE_CLIENT='中性'
TASK_ID=
MOUNT_POINT=/mnt/Release

# 在服务器上执行命令
function remote_cmd()
{
    local cmd=$1
    sshpass -p $USER_PASSWORD ssh $USER_NAME@$RELEASE_HOST "$cmd"
}


# 客户简称和客户名称对应关联表
declare -A CODE_CLIENT
CODE_CLIENT['RC']='中性'
CODE_CLIENT['YD']='原道'
CODE_CLIENT['HC']='恒晨'
CODE_CLIENT['KB']='酷比'
CODE_CLIENT['BDF']='白东峰'
CODE_CLIENT['RY']='瑞云'
CODE_CLIENT['HRA']='华瑞安'
CODE_CLIENT['JLC']='集力成'
CODE_CLIENT['LHC']='联合创'
CODE_CLIENT['CF']='诚丰'
CODE_CLIENT['WH']='伟恒'
CODE_CLIENT['PY']='普瑞'



# $1 path of scatter file
function parse_scatter()
{
    scatter=${1##*/}
	echo $scatter
    case $scatter in
        MT6737M_Android_scatter.txt)
            RELEASE_PLATFORM=MT8735BD
            ;;
        MT6771_Android_scatter.txt)
            RELEASE_PLATFORM=MT8788
            ;;
        MT6753_Android_scatter.txt)
            RELEASE_PLATFORM=MT8783T
            ;;
        MT6737T_Android_scatter.txt)
            RELEASE_PLATFORM=MT8735A
            ;;
        MT6735_Android_scatter.txt)
            RELEASE_PLATFORM=MT8735W
            ;;
        MT6735M_Android_scatter.txt)
            RELEASE_PLATFORM=MT8735MP
            ;;
        MT6755_Android_scatter.txt)
            RELEASE_PLATFORM=MT8785
            ;;
    esac
}

# U101_DC.N.V20.8.RC-V05.8735WP
# BOARD.ANDROID_VERSION.DDR.VERSION.PLATFORM.MODEM.TASK_ID
# 解析命名规则
function init_info()
{
    local OLD_IFS
    OLD_IFS="$IFS"
    IFS=.
    infos=(${1})
    echo "INFO -> ${infos[@]}"
    ROCO_BOARD=${infos[0]}
    if [[ ${infos[1]} =~ N ]]; then
        ANDROID_VERSION=7.0
    elif [[ ${infos[1]} =~ O ]]; then
        ANDROID_VERSION=8.1
    else
        ANDROID_VERSION=6.0
    fi
    echo "Info Size: ${#infos[@]}"
    # 数组长度的计算方法:  ${#infos[@]}
    for part in ${infos[@]} ; do
        if [[ $part =~ -V ]]; then
            client_code=$(echo $part | cut -d- -f1)
            RELEASE_CLIENT=${CODE_CLIENT[$client_code]}
        fi
        if echo $part | grep -w -E '[[:digit:]]{4}' ; then
            TASK_ID=$part
        fi
    done
    IFS="$OLD_IFS"

    echo "RELEASE_TYPE=$RELEASE_TYPE"
    echo "RELEASE_PLATFORM=$RELEASE_PLATFORM"
    echo "ANDROID_VERSION=$ANDROID_VERSION"
    echo "ROCO_BOARD=$ROCO_BOARD"
    echo "RELEASE_CLIENT=$RELEASE_CLIENT"
}

# 在服务器端创建目录
function remote_mkdir()
{
    local rv
    full_path="$RELEASE_BASE/$RELEASE_TYPE/$RELEASE_PLATFORM/$ANDROID_VERSION/$ROCO_BOARD/$RELEASE_CLIENT/$1"
    echo "MKDIR: $full_path"
    cmd="[ -d $full_path ] && echo REMOTE_EXISTS"
    rv=$(remote_cmd "$cmd")

    if [[ "$rv"  =~ "REMOTE_EXISTS" ]]; then
        echo "exists"
    else
        cmd="mkdir -p $full_path"
        remote_cmd "$cmd"
    fi
}

function get_system_prop()
{
	awk -F"=" '{if(/^ro.build.display.id/)print $2}' out/target/product/$1/system/build.prop
}

#$1 mtk_project   	tb8735ba1_bsp
function pack_rom()
{
	local mtk_project=$1
	local home=$PWD/../
	local rom_dir=$PWD/../ROM
	local out=out/target/product/$mtk_project
	local system_prop=$out/system/build.prop
	if [ ! -d "$out" ]; then
		RED "$out not found"
		return
	fi
	if [ ! -e "$out"/*_Android_scatter.txt ]; then
		RED "Android_scatter.txt NOT found in $out"
		return
	fi
	if [ ! -e "$system_prop" ]; then
		RED "$out/$system_prop"
		return
	fi
	display_id=$(awk -F"=" '{if(/^ro.build.display.id/)print $2}' $system_prop)
	dest_folder="$rom_dir/$display_id"
	if [ -e $dest_folder ]; then
		rm -rf $dest_folder
	fi
	mkdir -p $dest_folder
	mkdir -p $dest_folder/DB
	if [ -e $out/obj/CGEN/ ]; then
		apdb=$out/obj/CGEN/APDB*
		if [ -e $out/system/etc/mddb/ ]; then  # 6.0
			bplg=$out/system/etc/mddb/BPLGUInfoCustomApp*
		elif [ -e $out/system/vendor/etc/mddb ]; then  # 7.0
			bplg=$out/system/vendor/etc/mddb/BPLGUInfoCustomApp*
			if ls $bplg > /dev/null 2>&1 ; then  #
				RED "etc/mddb/BPLG OK"
			else   # 8785
				RED "You are using 8785 "
				bplg=$out/system/vendor/etc/mddb/MDDB*
			fi
		elif [ -e $out/vendor/etc/mddb ]; then   # 8.1
			bplg=$out/vendor/etc/mddb/BPLGUInfoCustomApp*
		else   # 8788
			bplg=vendor/mediatek/proprietary/modem/PF121_RDA_3M_GSM4_W1258_FDD3728/MDDB*
		fi
	fi
	cp $apdb $dest_folder/DB
	cp $bplg $dest_folder/DB
    cp "$out"/*_Android_scatter.txt $dest_folder
	pushd $out
	all_files=$(awk '/file_name/{T=$2;next}{if(/is_download/){if(/true/)print T;}}' *_Android_scatter.txt)
	for i in $all_files; do
		cp $i $dest_folder
	done
	for i in $(ls *verified* ); do
		cp $i $dest_folder
	done
	popd

}

function auto_pack()
{
	for project in $(ls out/target/product/) ; do
		pack_rom $project
	done
}
function remote_cp()
{
    # scp -r u101_yql_ili9881c_wxga tongz@192.168.122.228:~/bin/  scp可以直接复制目录的
    if [ -n "$TASK_ID" ]; then
        remote_mkdir $TASK_ID
    fi
    if [ -n "$TASK_ID" ]; then
        target_folder="$RELEASE_BASE/$RELEASE_TYPE/$RELEASE_PLATFORM/$ANDROID_VERSION/$ROCO_BOARD/$RELEASE_CLIENT/$TASK_ID/"
    else
        target_folder="$RELEASE_BASE/$RELEASE_TYPE/$RELEASE_PLATFORM/$ANDROID_VERSION/$ROCO_BOARD/$RELEASE_CLIENT/"
    fi
    echo "Target: $target_folder"
    echo "$target_folder/${1##*/}" >>~/bin/roco_platform_release.txt
    echo "sshpass -p $USER_PASSWORD scp -r $1 $USER_NAME@$RELEASE_HOST:$target_folder"
    sshpass -p $USER_PASSWORD scp -r "$1" "$USER_NAME@$RELEASE_HOST:$target_folder"
}

function start_copy()
{
    if [ ! -d "../ROM/$1" ]; then
        rm -rf ../ROM/$1
    fi
    remote_cp "../ROM/$1"
}

#$1 本地路径
function do_mount_upload()
{

    if [ -z $1 ]; then
        echo "No folder , "
        return
    fi
    echo "$1"
    name=$(basename $1)
	folder=$(dirname $1)
    echo "name=$name, folder=$folder"
	if [ ! -f $folder/$name.zip ] ;then
		pushd $folder
		zip -r -q -1 $name.zip $name
		popd
	fi
    for scatter in $(ls $1/*_Android_scatter.txt); do
        parse_scatter $1/$scatter
    done
    init_info $name

    if [ -n "$TASK_ID" ]; then
        target_folder="$MOUNT_POINT/$RELEASE_TYPE/$RELEASE_PLATFORM/$ANDROID_VERSION/$ROCO_BOARD/$RELEASE_CLIENT/$TASK_ID"
    else
        target_folder="$MOUNT_POINT/$RELEASE_TYPE/$RELEASE_PLATFORM/$ANDROID_VERSION/$ROCO_BOARD/$RELEASE_CLIENT"
    fi
    GREEN "$target_folder"
   if [ ! -d $target_folder ]; then
       mkdir -p $target_folder
   fi
	if [ ! -f $target_folder/$name ]; then
		cp -r $1 $target_folder
	fi
	if [ ! -f $target_folder/$name.zip ]; then
		cp -r $folder/$name.zip $target_folder
	fi
    target_folder="$target_folder/$name"
	remote_target=${target_folder//$MOUNT_POINT///${RELEASE_HOST}${RELEASE_BASE}}
	remote_target=${remote_target////\\}
	GREEN "\\$remote_target"
}

# @param $1 userdebug user eng
# @param $2 joya_project  joyasz8735b_3tb_n
# @param $3 roco_project LF808
# @param $4 modem
MK()
{
    source build/envsetup.sh
    lunch full_"$2"-"$1" $3
    make -j96  2>&1 | tee build_"$2-$3-$4".log
}

# @param $1 joya_project  joyasz8735b_3tb_n
# @param $2 ROCO_PROJECT LF808
function do_upload()
{
    DISPLAY_ID=$(awk -F"=" '{if(/^ro.build.display.id/)print $2}' "out/target/product/$1/system/build.prop")
    if [ -d "../ROM/$DISPLAY_ID" ]; then
        echo "RM: ../ROM/$DISPLAY_ID"
        rm -rf ../ROM/$DISPLAY_ID
    fi
    pack $1 $DISPLAY_ID
    # init_info $DISPLAY_ID
    # start_copy $DISPLAY_ID
}

# @param $1 joya_project
# @param $2 roco_project
# @param $3 modem
function do_update_config()
{
    roco_dir="device/mediateksample/$1/mid/$2"
    display_id=$(awk -F= '/ro.build.display.id/{print $2;}'  $roco_dir/system.prop)
    echo "DISPLAY.ID=$display_id"
    # Add TASK_ID
   # sed -i '/ro.build.display.id/s/=\(.*\)/=\1'.$4'/' $roco_dir/system.prop
    # change CLIENT_ID
    #sed -i '/ro.build.display.id/s/RC-V/'$5'-V/' $roco_dir/system.prop
    sed -i '/ro.build.display.id/s/=\(.*\)/=\1'.$3'/' $roco_dir/system.prop
    # udpate modem config

    projectconfig=$roco_dir/ProjectConfig.mk
    if [[ $3 =~ _5M_ ]]; then
        if [[ $1 =~ 35ba  ]]; then
            my_modem="$3-LWG_TSX $3-LTG_TSX"
        else
            my_modem="$3-LWG $3-LTG"
        fi
    else
         if [[ $1 =~ 35ba  ]]; then
            my_modem="$3-LWG_TSX"
        else
            my_modem="$3-LWG"
        fi
    fi
    if grep 'CUSTOM_MODEM' $projectconfig ; then
        sed -i "/CUSTOM_MODEM/s/=.*/= $my_modem/" $projectconfig
    else
        echo >> $projectconfig  # Add an empty line to make sure on a new line
        echo "CUSTOM_MODEM=$my_modem" >> $projectconfig
    fi
    if grep 'MTK_PROTOCOL1_RAT_CONFIG' $projectconfig; then
        if [[ $3 =~ _5M_ ]]; then
            sed -i "/MTK_PROTOCOL1_RAT_CONFIG/s|=.*|= Lf/Lt/W/G|" $projectconfig
        else
            sed -i "/MTK_PROTOCOL1_RAT_CONFIG/s|=.*|= Lf/W/G|" $projectconfig
        fi
    else
        if [[ $3 =~ _5M_ ]]; then
            echo >> $projectconfig  # Add an empty line to make sure on a new line
            echo "MTK_PROTOCOL1_RAT_CONFIG = Lf/Lt/W/G" >> $projectconfig
        else
            echo >> $projectconfig  # Add an empty line to make sure on a new line
            echo "MTK_PROTOCOL1_RAT_CONFIG = Lf/W/G"  >> $projectconfig
        fi
    fi
    git diff device/mediateksample/$1/mid/$2 > $1_$2_$3.diff
}

# @param $1 joya_project
# @param $2 roco_project
# @param $3 modem
function do_make()
{
    do_update_config $1 $2 $3
    MK userdebug $1 $2 $3
    if [ $? != 0 ]; then
        echo "Make $1 $2 $3 Fail"
        return 1
    fi
    auto_pack
    mv out ../out-$1_$2_$3
#    do_upload $1 $2
}

# 编译一个项目并上传到指定的目录
# $1  joya_project
# $2  mid_project
function make_project()
{
	if [ $# -lt 2 ]; then
		RED "Usage: make_project joya_project mid_project"
		return
	fi
    MK userdebug $1 $2 "RC"
	auto_pack
	do_mount_upload ../ROM/$(get_system_prop $1)
}

function do_8735bd()
{
    ALL_MODEMS=(LF705H_RDA_5M_GSM4_W18_TDS3439_TDD38394041_FDD13720
        LF705H_RDA_3M_GSM4_W25_FDD24717
        LF710T_RDA_3M_GSM4_W18_FDD13720
        )

    ALL_PROJECTS=(tb8735ba1_bsp )
    ALL_ROCO_PROJECTS=(LF705H LF710T_GMSO)
    modem_base=vendor/mediatek/proprietary/modem
    #rm -rf out;
    for project in ${ALL_PROJECTS[@]}; do
        for modem in ${ALL_MODEMS[@]}; do
            echo "project=$project, modem=$modem"
            # do_update_config $project LF705H $modem
            for roco_project in ${ALL_ROCO_PROJECTS[@]}; do
                git checkout .
                do_make $project $roco_project $modem
               # mv out ../$project-LF705H-$modem
            done
        done
    done
}

upload_dir=

while getopts ":u:pm:" opt; do
    case $opt in
        u )
            upload_dir=$OPTARG
            echo $upload_dir
			if [[ -n "$upload_dir" ]]; then
				do_mount_upload $upload_dir
			fi
            ;;
		p )
			auto_pack
			;;
		m )
			echo "$OPTARG"
			make_project ${OPTARG//,/ }
			;;
		*)
			;;
    esac
done
